const express = require('express');
const route = express.Router();
const pool = require('../pool')
// 注册
route.post('/register', (req, res) => {
  let uname = req.body.uname;
  let upwd = req.body.upwd;
  let obj = req.body;
  console.log(obj);

  //检测两次输入的密码是否一致
  if (obj.upwd != obj.upwd2) {
    
    return res.json({ code: 406, msg: "两次输入的密码不一致,请重新输入" });
  }
 
  //检测密码是否为空
  if (!obj.upwd) {
    
    return res.json({ code: 402, msg: "upwd required" });
  }
  //检测重复密码是否为空
  if (!obj.upwd2) {
   
    return res.json({ code: 403, msg: "upwd2 required" });
  }
  // 检测完毕删除
  delete obj.upwd2;
  //检测电话是否为空
  if (!obj.phone) {
    
    return res.json({ code: 404, msg: "phone required" });
  }
  //检测手机号的合法性(正则)
  var pt = /^1[3-9]\d{9}$/;
  if (!pt.test(obj.phone)) {
    
    return res.json({ code: 405, msg: "手机号格式非法" });
    
  }
  let sql = "insert into user set ?";
  pool.query(sql, [obj], (err, result) => {
    if (err) throw err;
    console.log(result);
    if (result.affectedRows > 0) {
     
      return res.json({
        code: 200,
        msg: "success",
        data: { uid: result.insertId, uname: obj.uname }
      });
      
    }
    else {
      res.json({
        code: 400,
        msg: "fail",
        data: result
      });
    }
  }
  );
});
// 登录
route.post('/login', (req, res) => {
  var obj = req.body;

  //检测用户名是否为空
  if (!obj.uname) {
    return res.json({ code: 401, msg: "uname required" });
  }
  //检测密码是否为空
  if (!obj.upwd) {
   return res.json({ code: 402, msg: "upwd required" });
  }

  //查询语句
  let sql = "SELECT * FROM user WHERE (uname=? AND upwd=? ) or (phone=? AND upwd=?) LIMIT 1";
  pool.query(sql, [obj.uname, obj.upwd,obj.uname, obj.upwd], (err, result) => {
    if (err) throw err;
    console.log(result);
    if (result.length > 0) {
      res.json({ code: 200, msg: "success", data: result });
    } else {
      res.json({ code: 301, msg: "no user" });
    }
  });
})
// 检测用户名是否存在
route.post("/check_uname",(req,res)=>{
  var obj=req.body;
  console.log(obj);
  if(!obj.uname){
    return res.json({code:300,msg:"uname is required"})
  }
  let sql="select count(*) as num from user where uname=?"
  pool.query(sql,[obj.uname],(err,result)=>{
    console.log(result)
    if(result[0].num>0){return res.json({code:301,msg:"user exist"})}
    else{ return res.json({code:200,msg:"user not exist"})}
  })
})
// 检测手机是否存在
route.post("/check_phone",(req,res)=>{
  var obj=req.body;
  console.log(obj);
  if(!obj.phone){
    return res.json({code:300,msg:"phone is required"})
  }
  let sql="select count(*) as num from user where phone=?"
  pool.query(sql,[obj.phone],(err,result)=>{
    console.log(result)
    if(result[0].num>0){return res.json({code:301,msg:"phone exist"})}
    else{ return res.json({code:200,msg:"phone not exist"})}
  })
})
module.exports = route;